import React, { Component } from 'react'
import { Layout, Menu } from 'antd';
import { withRouter } from 'react-router-dom'

import { IconFont } from '../../components'
import { adminRoutes } from '../../routes'

const { SubMenu } = Menu;
const { Sider } = Layout;

const formatMenu = (menus) => {
  return menus.filter(item => item.isNav).map(item => {
    if(item.children) {
      return (
        <SubMenu key={item.pathname} icon={<IconFont type={item.icon} />} title={item.title}>
          {
            formatMenu(item.children)
          }
        </SubMenu>
      )
    }
    return (
      <Menu.Item key={item.pathname} icon={<IconFont type={item.icon} />} >{item.title}</Menu.Item>
    )
  })
}
/**
 * @param {String} path 当前路由路劲
 * @returns {Array} 默认打开菜单的数组
 * @example '/admin/setting/menusetting' => ['/admin','/admin/setting', '/admin/setting/menusetting']
 */
const formatPath = (path) => {
  return path.split('/').reduce((acc, cur) => {
    if(cur){
      return acc.concat(`${acc[acc.length - 1] || ''}/${cur}`)
    } else {
      return acc
    }
  },[])
}

@withRouter
class MySider extends Component {
  constructor(props) {
    super(props)
    this.state = {
      defaultSelectedKeys: ['1']
    }
  }

  static getDerivedStateFromProps (props) {
    return {
      defaultSelectedKeys: [props.location.pathname],
      defaultOpenKeys: formatPath(props.location.pathname)
    }
  }

  handleMenuClick = ({key}) => {
    this.props.history.push(key)
  }
  render() {
    return (
      <Sider width={200} className="site-layout-background">
        <Menu
          onClick={this.handleMenuClick}
          mode="inline"
          defaultSelectedKeys={this.state.defaultSelectedKeys}
          defaultOpenKeys={this.state.defaultOpenKeys}
          style={{ height: '100%', borderRight: 0 }}
        >
          {
            formatMenu(adminRoutes)
          }
        </Menu>
      </Sider>
    )
  }
}

export default MySider
